package com.bigevent.bigevent.controller;

import com.bigevent.bigevent.entity.Result;
import com.bigevent.bigevent.entity.User;
import com.bigevent.bigevent.po.UpdatePwdPo;
import com.bigevent.bigevent.service.UserService;
import com.bigevent.bigevent.utils.UserUtil;
import jakarta.validation.constraints.Pattern;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author yangxudong
 * @description: 用户controller
 * @date 2024/2/3 12:51
 */
@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        userService.register(username, password);
        return Result.success();
    }

    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        return Result.success(userService.login(username, password));
    }

    // 该接口用于获取当前已登录用户的详细信息
    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        User user = userService.getUser(UserUtil.getUsername());
        return Result.success(user);
    }

    @PutMapping("/update")
    public Result updateUserInfo(@RequestBody @Validated User user) {
        userService.updateUserInfo(user);
        return Result.success();
    }

    @PatchMapping("/updateAvatar")
    public Result updateAvatar(String avatarUrl) {
        userService.updateAvatar(UserUtil.getUsername(), avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody @Validated UpdatePwdPo updatePwdPo, @RequestHeader("Authorization") String token) {
        userService.updatePwd(UserUtil.getUsername(), updatePwdPo.getOldPwd(), updatePwdPo.getNewPwd(), updatePwdPo.getRePwd(), token);
        return Result.success();
    }
}
